package br.usp.pcs.basys2.memory;

import br.usp.pcs.basys2.BasysProcess;

public class MemoryPartition implements Comparable<MemoryPartition> {

	private BasysProcess basysProcess; 
	private Integer startBlock;
	private Integer endBlock;
	
	public Integer getStartBlock() {
		return startBlock;
	}
	
	public void setEmpty(){
		this.basysProcess = null;
	}

	public void setStartBlock(Integer startBlock) {
		this.startBlock = startBlock;
	}

	public boolean isEmpty(){
		return basysProcess==null;
	}
	
	public Integer getSize(){
		return endBlock-startBlock;
	}

	public MemoryPartition(BasysProcess basysProcess, Integer startBlock) {
		super();
		if (basysProcess==null) throw new IllegalArgumentException();
		this.basysProcess = basysProcess;
		this.startBlock = startBlock;
		this.endBlock = startBlock+basysProcess.getSize()-1;
	}

	public MemoryPartition(Integer startBlock, Integer endBlock) {
		super();
		this.startBlock = startBlock;
		this.endBlock = endBlock;
		this.basysProcess = null;
	}

	public BasysProcess getProcess() {
		return basysProcess;
	}

	public Integer getEndBlock() {
		return endBlock;
	}

	public void setEndBlock(Integer endBlock) {
		this.endBlock = endBlock;
	}
	
	@Override
	public String toString() {
		String result = "startBlock: " + startBlock;
		result += " segment: " + (basysProcess==null?"null":basysProcess.getId());
		result += " endBlock: " + endBlock ;
		
		return result ;
	}

	public int compareTo(MemoryPartition o) {
			return (int)(this.startBlock-o.startBlock);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((basysProcess == null) ? 0 : basysProcess.hashCode());
		result = prime * result
				+ ((endBlock == null) ? 0 : endBlock.hashCode());
		result = prime * result
				+ ((startBlock == null) ? 0 : startBlock.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final MemoryPartition other = (MemoryPartition) obj;
		if (basysProcess == null) {
			if (other.basysProcess != null)
				return false;
		} else if (!basysProcess.equals(other.basysProcess))
			return false;
		if (endBlock == null) {
			if (other.endBlock != null)
				return false;
		} else if (!endBlock.equals(other.endBlock))
			return false;
		if (startBlock == null) {
			if (other.startBlock != null)
				return false;
		} else if (!startBlock.equals(other.startBlock))
			return false;
		return true;
	}
	
	

}
